package org.coderk.mybatis.mapper.interceptor;

import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Objects;

/** 在启动类中的 codertApplicationRunner 中使用了
 * @author: TanJingyu
 * @create: 2021-06-08 10:29
 **/
@Intercepts({@Signature(
        type= Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class ExamplePlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = null;

        Object[] args = invocation.getArgs();
        for (Object arg : args) {
            if (arg instanceof MappedStatement) {
                mappedStatement = (MappedStatement) arg;
            }
        }

        if (Objects.nonNull(mappedStatement)) {
            Field sqlSourceField = ReflectionUtils.findField(mappedStatement.getSqlSource().getClass(), "sqlSource");
            assert sqlSourceField != null;
            ReflectionUtils.makeAccessible(sqlSourceField);
            StaticSqlSource sqlSource = (StaticSqlSource) sqlSourceField.get(mappedStatement.getSqlSource());
            Field sql = ReflectionUtils.findField(sqlSource.getClass(), "sql");
            assert sql != null;
            ReflectionUtils.makeAccessible(sql);
            ReflectionUtils.setField(sql, sqlSource, sql.get(sqlSource) + " where u.id = 1");
        }

        return invocation.proceed();
    }
}
